package com.tangruojie.service.impl;

import com.alibaba.fastjson2.JSON;
import com.tangruojie.constant.RedisConstant;
import com.tangruojie.domain.LoginUser;
import com.tangruojie.service.LoginService;
import com.tangruojie.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    public final AuthenticationManager authenticationManager;

    private final JwtUtils jwtUtils;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String, String> login(LoginUser loginUser) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser.getUserName(), loginUser.getPassword());
        Authentication authenticate;
        try {
            authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        } catch (AuthenticationException e) {
            throw new RuntimeException("用户名或密码错误");
        }
        UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authenticate.getPrincipal();
        String id = userDetailsImpl.getUser().getId().toString();
        String generateToken = jwtUtils.generateToken(id);
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_TOKEN + id, JSON.toJSONString(userDetailsImpl));
        return Map.of(RedisConstant.TOKEN, generateToken);
    }

}
